<template>
  <div>
    <Alert v-if="alert" v-bind="alert" @close="closeAlert"/>
    <h1>用户列表</h1>
    <!-- 搜索框 -->
    <input type="text" class="form-control" v-model="searchItem" placeholder="请输入用户姓名" @input="changeHandle">
    <!-- 表格：显示用户信息 -->
     <table class="table table-striped table-bordered">
      <thead>
        <tr>
          <th>姓名</th>
          <th>年龄</th>
          <th>联系方式</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in list" :key="item.id">
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.phone }}</td>
          <td>
            <router-link :to="`/detail/${item.id}`">详情</router-link>
          </td>
        </tr>
      </tbody>
     </table>
  </div>
</template>

<script setup>
import { onMounted,ref,computed } from 'vue';
import { getUserListApi } from '@/api/userApi';
import Alert from '../components/Alert.vue';
import { useRoute } from 'vue-router';

const userList = ref([]);

const searchItem = ref('');
const searchList = ref([]);
const alert = ref(null);
const route = useRoute();

const list = computed(() => searchItem.value ? searchList.value : userList.value);


onMounted(() => {
  getUserListApi().then(({data}) => {
    userList.value = data;
  });
  if(route.query && route.query.alert) {
    alert.value = route.query;
  }
});

function changeHandle() {
  searchList.value = userList.value.filter((userItem) => userItem.name.includes(searchItem.value));
}

function closeAlert() {
  alert.value = null;
}


</script>

<style scoped></style>
